package client

import (
	"4-26zk/comment/proto/product"
	"context"
	"fmt"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, client product.ProductClient) (interface{}, error)

func ProductClient(ctx context.Context, handler Handler) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
	}
	defer conn.Close()
	// 2. 实例化gRPC客户端
	client := product.NewProductClient(conn)
	// 3.组装请求参数
	req, _ := handler(ctx, client)
	return req, nil
}

func ProductCreate(ctx context.Context, req *product.ProductCreateReq) (*product.ProductCreateResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, client product.ProductClient) (interface{}, error) {
		create, err := client.ProductCreate(ctx, req)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductCreateResp), nil
}
func ProductOtherInfoCreate(ctx context.Context, req *product.ProductOtherInfoCreateReq) (*product.ProductOtherInfoCreateResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, client product.ProductClient) (interface{}, error) {
		create, err := client.ProductOtherInfoCreate(ctx, req)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductOtherInfoCreateResp), nil
}
func ProductSpecificationsCreate(ctx context.Context, req *product.ProductSpecificationsCreateReq) (*product.ProductSpecificationsCreateResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, client product.ProductClient) (interface{}, error) {
		create, err := client.ProductSpecificationsCreate(ctx, req)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductSpecificationsCreateResp), nil
}
func ProductList(ctx context.Context, req *product.ProductListReq) (*product.ProductListResp, error) {
	client, err := ProductClient(ctx, func(ctx context.Context, client product.ProductClient) (interface{}, error) {
		create, err := client.ProductList(ctx, req)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*product.ProductListResp), nil
}
